package com.neulogistics.core.customercenter.api.application.integrationevent.handler;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.blackto.lib.eventbus.abstraction.IIntegrationEventHandler;
import com.neulogistics.core.customercenter.api.application.integrationevent.subscribe.InventoryCheckedIntegrationEvent;
import com.neulogistics.core.customercenter.domain.model.aggregate.Order;
import com.neulogistics.core.customercenter.domain.model.enumeration.OrderStatus;
import com.neulogistics.core.customercenter.domain.repository.IOrderRepository;
import com.neulogistics.core.customercenter.infrastructure.persistence.orm.po.OrderPO;
import com.neulogistics.core.customercenter.infrastructure.persistence.orm.service.IOrderPOService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

@Component
public class InventoryCheckedIntegrationEventHandler implements IIntegrationEventHandler<InventoryCheckedIntegrationEvent> {
    @Resource
    IOrderRepository orderRepository;

    @Resource
    IOrderPOService orderPOService;

    @Override
    public CompletableFuture<Void> handle(InventoryCheckedIntegrationEvent event) {
        // 查询订单
        Order order = orderRepository.findById(event.orderId);
        // 货不足，改为缺货
        if(!event.isAdequate){
            order.setOrderStatus(OrderStatus.Out_Of_Stock);
            orderRepository.save(order);
            return CompletableFuture.completedFuture(null);
        }
        // 货足，改为待出库
        LambdaUpdateWrapper<OrderPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(OrderPO::getOrderId, event.orderId)
                .lt(OrderPO::getOrderStatus, OrderStatus.Waiting_Out_Of_Warehouse.id)
                .set(OrderPO::getOrderStatus, OrderStatus.Waiting_Out_Of_Warehouse.id);
        orderPOService.update(updateWrapper);
        return CompletableFuture.completedFuture(null);
    }
}
